<template>
  <div class="table-gl-w">
    <div class="search-con search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="sizeChange(20)">
        <template #headerLeft>
          <a-button type="primary" @click="show('add')" v-if="$authPass('express.template.saveOrUpdate')">添加模板</a-button>
          <a-button class="gray-outline ml10" @click="batchUpdate(false, 'mul')" v-if="$authPass('express.template.updateStatus')">批量停用</a-button>
          <a-button class="gray-outline ml10" @click="batchUpdate(true, 'mul')" v-if="$authPass('express.template.updateStatus')">批量启用</a-button>
        </template>
        <template #tableBody>
          <a-table size="mini" class="table-singe-line show-border-table" ref="table" :loading="loading" row-key="id" v-model:selected-keys="ids" :row-selection="rowSelection" :data="tableList" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ record, rowIndex }" :width="40">
                {{ rowIndex + 1 }}
              </a-table-column>
              <a-table-column title="模板名称" #cell="{ record, rowIndex }" :width="80">
                {{ record.name }}
              </a-table-column>
              <a-table-column title="物流优先级" #cell="{ record, rowIndex }" :width="80">
                {{ record.shipLevel == 'Standard' ? '普通' : '加急' }}
              </a-table-column>
              <a-table-column title="计费维度" #cell="{ record, rowIndex }" :width="80">
                {{ filterType(record.chargeType) }}
              </a-table-column>
              <a-table-column title="计费方式" #cell="{ record, rowIndex }" :width="80">
                {{ record.chargeMethod == 'FIRST_CONTINUE' ? '首重续重' : '重量段' }}
              </a-table-column>
              <a-table-column title="国家/地区" #cell="{ record, rowIndex }" :width="80">
                <TextHidden :rowsWidth="75"> {{ getCounrtyName(record.addressesList) }}</TextHidden>
              </a-table-column>
              <a-table-column title="发货仓" #cell="{ record, rowIndex }" :width="80">
                <TextHidden :rowsWidth="75">{{ getWareHouseName(record) }}</TextHidden>
              </a-table-column>
              <a-table-column title="创建人" #cell="{ record, rowIndex }" :width="80">
                {{ record.createUname }}
              </a-table-column>
              <a-table-column title="创建日期" #cell="{ record, rowIndex }" :width="140">
                {{ $setTime(record.gmtCreate) }}
              </a-table-column>
              <a-table-column title="更新人" #cell="{ record, rowIndex }" :width="80">
                {{ record.writeUname }}
              </a-table-column>
              <a-table-column title="更新日期" #cell="{ record, rowIndex }" :width="140">
                {{ $setTime(record.gmtWrite) }}
              </a-table-column>
              <a-table-column title="状态" #cell="{ record, rowIndex }" :width="60">
                <a-switch :disabled="!$authPass('express.template.updateStatus')" v-model="record.enable" @change="batchUpdate($event, 'single', record.id)">
                  <template #checked> 开 </template>
                  <template #unchecked> 关 </template>
                </a-switch>
              </a-table-column>
              <a-table-column title="操作" #cell="{ record, rowIndex }" :width="40">
                <a-button type="text" @click="show('edit', record.id)" v-if="$authPass('express.template.saveOrUpdate')">编辑</a-button>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import { pageExpressFreightTemplate, findWarehouseListByParam, updateEnableExpressFreightTemplate } from '@/api/warehouse'
  import { Modal, Message } from '@arco-design/web-vue'
  import { useRouter } from 'vue-router'
  import { countriesOptions } from '@/utils/countries'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'

  export default defineComponent({
    components: { FilterTable, TableWrap },
    setup() {
      const route = useRouter()
      const data: any = reactive({
        filterItem: [
          {
            key: 'nameList',
            label: '模板名称',
            value: ref(),
            type: 'input_search',
            width: 180,
          },
          {
            key: 'shipLevelList',
            label: '物流优先级',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [
              { label: '普通', value: 'Standard' },
              { label: '加急', value: 'Expedited' },
            ],
          },
          {
            key: 'chargeTypeList',
            label: '计费维度',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [
              { label: '按毛重', value: 'WEIGHT' },
              { label: '按体积', value: 'VOLUME' },
              { label: '发货按单数', value: 'ORDER' },
              { label: '按货品件数', value: 'PIECE' },
            ],
          },
          {
            key: 'chargeMethodList',
            label: '计费方式',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [
              { label: '重量段', value: ' RANGE' },
              { label: '首重续重', value: 'FIRST_CONTINUE' },
            ],
          },
          {
            key: 'countryCodeList',
            label: '国家/地区',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'warehouseCodeList',
            label: '发货仓',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [
              { label: '重量段', value: '1' },
              { label: '首重续重', value: '2' },
            ],
            attrs: {
              'allow-search': true,
            },
          },
        ],
        tableList: [],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        loading: false,
        searchValue: {},
        type: 'add',
        info: {},
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
        ids: [],
        countryList: countriesOptions,
      })

      const searchByVal = (info: any) => {
        data.searchValue = {}
        data.searchValue = info
        data.pageNation.pageNum = 1
        getList()
      }

      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const getList = async () => {
        let params = {
          ...data.searchValue,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        const res: any = await pageExpressFreightTemplate(params)
        if (res.code == 'SUCCESS') {
          data.tableList = res.data?.records || []
          data.pageNation.total = res.data.total
        }
        data.loading = false
      }

      const show = (type: string, id?: string) => {
        route.push({
          path: '/warehouse/logisticsSetting/feeTempalte/addTemDetail',
          query: {
            type,
            id,
          },
        })
      }

      const filterType = (val: string) => {
        let text = ''
        switch (val) {
          case 'WEIGHT':
            text = '按毛重'
            break
          case 'VOLUME':
            text = '按体积'
            break
          case 'ORDER':
            text = '发货按单数'
            break
          case 'PIECE':
            text = '按货品件数'
            break
        }
        return text
      }

      const del = (val: string) => {
        Modal.error({
          title: '提示',
          content: '是否删除？',
          titleAlign: 'start',
          cancelText: '取消',
          hideCancel: false,
          onBeforeOk: async (done) => {
            let params = {
              enable: true,
              idList: [],
            }
            const res: any = await updateEnableExpressFreightTemplate(params)
            if (res.code == 'SUCCESS') {
              done(true)
              Message.success('删除成功')
              sizeChange(20)
            }
          },
        })
      }

      const getWareHouse = async () => {
        const res = await findWarehouseListByParam()
        let arr = res?.data || []
        arr.map((e: any) => {
          e.label = e.warehouseName
          e.value = e.warehouseCode
          return e
        })
        data.filterItem[5].optionItems = arr
      }
      const getCountry = () => {
        let arr = countriesOptions
        arr.map((e: any) => {
          e.label = e.name
          e.value = e.short
          return e
        })
        data.filterItem[4].optionItems = arr
      }

      const getCounrtyName = (list: any) => {
        if (list) {
          let arr: Array<string> = []
          list.forEach((el: any) => {
            let obj: any = countriesOptions.find((e: any) => e.short == el.countryCode)
            if (obj) arr.push(obj.name)
          })

          return arr.join(',')
        }
      }

      const getWareHouseName = (item: any) => {
        let arr = item.warehouseList
        return arr.map((e: any) => e.name).join(',')
      }

      const batchUpdate = async (val: boolean, type: string, id?: string) => {
        if (type == 'mul') {
          if (!data.ids[0]) {
            return Message.error('请选择需要更改状态的数据')
          }

          Modal.error({
            title: '提示',
            content: `是否更改状态为${val ? '启用' : '禁用'}？`,
            titleAlign: 'start',
            cancelText: '取消',
            hideCancel: false,
            onOk: async () => {
              let params = {
                enable: val,
                idList: data.ids,
              }
              const res: any = await updateEnableExpressFreightTemplate(params)
              if (res.code == 'SUCCESS') {
                Message.success(`${val ? '启用' : '禁用'}成功`)
                data.ids = []
                sizeChange(20)
              }
            },
          })
        } else {
          let params = {
            enable: val,
            idList: [id],
          }
          const res: any = await updateEnableExpressFreightTemplate(params)
          if (res.code == 'SUCCESS') {
            Message.success(`${val ? '启用' : '禁用'}成功`)
            data.ids = []
            sizeChange(20)
          }
        }
      }

      getList()
      getCountry()
      getWareHouse()

      return {
        ...(toRefs(data) as any),
        changePage,
        sizeChange,
        searchByVal,
        filterType,
        show,
        del,
        getCounrtyName,
        getWareHouseName,
        batchUpdate,
      }
    },
  })
</script>

<style lang="less" scoped></style>
